home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 7_10.lha / 7_10 / test1.c < prev    next >
C/C++ Source or Header  |  1993-08-08  |  2KB  |  83 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. * based on cfront 2.0 b5 demo program alph.C */
  6. include <debug.h>    /* DELETE */
  7. *ident    "@(#)ctrans:demo/task/alph.C    1.1" */
  8. **************************************************************************
  9.         Copyright (c) 1984 AT&T
  10.           All Rights Reserved
  11.  
  12. THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T
  13.  
  14. The copyright notice above does not evidence any
  15. actual or intended publication of such source code.
  16.  
  17. ****************************************************************************/
  18. / Demonstration of two processes communicating via semaphores.
  19.  
  20. include <process.h>
  21. define K 10
  22.  
  23. lass Semaphore : public process_object
  24.  
  25.    int    sigs;
  26. ublic:
  27.     Semaphore(int i =0) { sigs = i; }
  28.    int        pending();
  29.    void    wait();
  30.    void    signal() { if (sigs++ == 0) alert(); }
  31. ;
  32.  
  33. oid Semaphore::wait()
  34.  
  35.    for (;;)
  36. {
  37. if (--sigs >= 0)
  38.     return;
  39. sigs++;
  40. this_process()->pause(this);
  41. }
  42.  
  43.  
  44. nt Semaphore::pending()
  45.  
  46.    return sigs <= 0;
  47.  
  48.  
  49. emaphore* sema[2];
  50.  
  51. lass Test : public process
  52.  
  53.    int svi;
  54.  
  55. ublic:
  56.    Test(int i) : (i ? "Alphonse" : "Gaston") { svi = i; }
  57.    long main();
  58. ;
  59.  
  60. ong Test::main()
  61.  
  62.    for (register int n = K / 2; n--; )
  63. {
  64. sema[!svi]->wait();
  65. sema[svi]->signal();
  66. printf("%s: %d\n", svi ? "Alphonse" : "Gaston", n);
  67. }
  68.  
  69.    return 0;    // "return" sets the exitcode
  70.  
  71.  
  72. ain()
  73.  
  74.    sema[0] = new Semaphore(1);
  75.    sema[1] = new Semaphore;
  76.    (new Test(0))->exec();    // create "Gaston" process; switch to it
  77.    (new Test(1))->exec();    // create "Alphonse" process; switch to it
  78.    printf("back in main\n");
  79.    main_process()->exit(0); // terminate main process
  80.    printf("should not get here\n");
  81.    return 0;
  82.  
  83.